<?php
/**
 *
 * BEGIN PlayerAdmin.php
 *
 *
 * @Description: This class provides Player data administration functionality for Dazzler
 * @Authors: Thato Selebogo, Wits University
 * @Copyright: © Wits University 2011 - All Rights Reserved
 * @License: BSD License (http://www.linfo.org/bsdlicense.html)
 *
 *
 * BEGIN CHANGELOG
 * Developers working on thee files are REQUIRED to maintain this CHANGELOG.
 * Please ensure you follow the Changelog Guidelines: http://code.google.com/p/dazzler/wiki/DazzlerDevelopGuideline?ts=1315476570&updated=DazzlerDevelopGuideline
 * !==================================================================================================================================================================
 *
 * VERSION 1.0.0
 * 	+ File Created, Thato Selebogo, 21 September 2011
 *
 *
 * ================================================================================================================================================================!
 * END CHANGELOG
 */
/* * *****************************************************************************************************************************************************************
 *
 * BEGIN Direct Call Check
 *
  /***************************************************************************************************************************************************************** */
class PlayerAdmin extends baseClass {

    public $_databaseAdapter;
    protected $_databaseTable;

    /**
     * Class constructor
     */
    public function __construct() {

        // Get database adapter and error logger from the base class
        $this->_databaseAdapter = parent::databaseAdapter();
        parent::parseLanguageErrorLogFile();
    }

    //Insert player into player pool
    public function insertPlayer($firstName, $lastName, $teamPoolId, $birthDate = '', $birthPlace = '', $nickName = '', $heigth = '', $profile = '', $fieldingPos ='', $bowlingStyle = '', $batStyle = '', $isBatSpecialist = FALSE) {
        // make sure manditory fields have been entered
        if (empty($firstName)) {
            die($this->lang_ini_array['ERRORS']['BlankFirstNameError']);
        }

        if (empty($lastName)) {
            die($this->lang_ini_array['ERRORS']['BlankLastNameError']);
        }

        //Check against duplicates
        $this->_databaseTable = 'PLAYER_POOL';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE PLAYER_POOL_FNAME = '$firstName' AND PLAYER_POOL_LNAME = '$lastName'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) > 0) {
            return false;
        }

        $playerData = array(
            'PLAYER_POOL_ID' => '',
            'TEAM_POOL_TEAM_POOL_ID' => $teamPoolId,
            'PLAYER_POOL_FNAME' => $firstName,
            'PLAYER_POOL_LNAME' => $lastName,
            'PLAYER_POOL_DOB' => $birthDate,
            'PLAYER_POOL_POB' => $birthPlace,
            'PLAYER_POOL_AGE' => '',
            'PLAYER_POOL_NNAME' => $nickName,
            'PLAYER_POOL_HT' => $heigth,
            'PLAYER_POOL_PROFL' => $profile,
            'PLAYER_POOL_FLDNG' => $fieldingPos,
            'PLAYER_POOL_BOWLSTYL' => $bowlingStyle,
            'PLAYER_POOL_BATSTYL' => $batStyle,
            'PLAYER_POOL_BATSPECILST' => $isBatSpecialist);

        $this->_databaseTable = 'PLAYER_POOL';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $playerData);

        //Calculate age
        if (!empty($birthDate)) {
            $query = " SELECT DATEDIFF(CURDATE(), '$birthDate') / 365.25 AS age";
            $this->_databaseAdapter->query($query);
            $row = $this->_databaseAdapter->fetch();
            extract($row);
            $age =  $row['age'];

            //Round up
            $age = ceil($age);
            $query = "UPDATE $this->_databaseTable SET PLAYER_POOL_AGE='$age' WHERE PLAYER_POOL_ID='$id'";
            $this->_databaseAdapter->query($query);
       }
        return $id;
    }

        //Register player for game
    public function registerPlayer4Game($gameId, $playerPoolId, $batOrder, $isPlayerBowler = FALSE, $isCaptain = FALSE) {
        

        //Check against duplicates
        $this->_databaseTable = 'PLAYER';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE PLAYER_POOL_PLAYER_POOL_ID = '$playerPoolId' and TEAM_GAME_GAME_ID = '$gameId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) > 0) {
            return false;
        }


         $query = "SELECT tmp.TEAM_POOL_ID
                  FROM PLAYER_POOL AS pp
                  LEFT JOIN TEAM_POOL AS tmp ON pp.TEAM_POOL_TEAM_POOL_ID = tmp.TEAM_POOL_ID
                  WHERE pp.PLAYER_POOL_ID = '$playerPoolId'";

        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $teamPoolId = $resultArray['TEAM_POOL_ID'];

        $query = "SELECT TEAM_ID FROM TEAM
                  WHERE TEAM_POOL_TEAM_POOL_ID = '$teamPoolId' AND GAME_GAME_ID = '$gameId'";

        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $teamId = $resultArray['TEAM_ID'];

        $playerData = array(
            'PLAYER_ID' => '',
            'TEAM_TEAM_ID' => $teamId,
            'TEAM_GAME_GAME_ID' => $gameId,
            'PLAYER_POOL_PLAYER_POOL_ID' => $playerPoolId,
            'PLAYER_BAT_ORDR' => $batOrder,
            'PLAYER_CAPT' => $isCaptain);

        $this->_databaseTable = 'PLAYER';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $playerData);

        //Insert player into BATSMAN table
        $batsmanData = array(
            'BATSMAN_ID' => '',
            'PLAYER_PLAYER_ID' => $id,
            'PLAYER_TEAM_TEAM_ID' => $teamId,
            'PLAYER_TEAM_GAME_GAME_ID' => $gameId);

        $this->_databaseTable = 'BATSMAN';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $batsmanData);

        //Insert player into BOWLER table
        if ($isPlayerBowler == TRUE) {
            $bowlerData = array(
            'BOWLER_ID' => '',
            'PLAYER_PLAYER_ID' => $id,
            'PLAYER_TEAM_TEAM_ID' => $teamId,
            'PLAYER_TEAM_GAME_GAME_ID' => $gameId);

        $this->_databaseTable = 'BOWLER';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $batsmanData);
        return true;
        }

        return true;
    }



        public function updatePlayerDetails($id, $firstName, $lastName, $teamPoolId, $birthDate = '', $birthPlace = '', $nickName = '', $heigth = '', $profile = '', $fieldingPos ='', $bowlingStyle = '', $batStyle = '') {
        // make sure manditory fields have been entered
        if (empty($firstName)) {
            die($this->lang_ini_array['ERRORS']['BlankFirstNameError']);
        }

        if (empty($lastName)) {
            die($this->lang_ini_array['ERRORS']['BlankLastNameError']);
        }

        if ($_SESSION['admin_level'] == 0) {
            die($this->lang_ini_array['ERRORS']['AdminLevelError']);
        }

        $playerData = array(
            'PLAYER_POOL_FNAME' => $firstName,
            'PLAYER_POOL_LNAME' => $lastName,
            'PLAYER_POOL_DOB' => $birthDate,
            'PLAYER_POOL_POB' => $birthPlace,
            'PLAYER_POOL_AGE' => '',
            'PLAYER_POOL_NNAME' => $nickName,
            'PLAYER_POOL_HT' => $heigth,
            'PLAYER_POOL_PROFL' => $profile,
            'PLAYER_POOL_FLDNG' => $fieldingPos,
            'PLAYER_POOL_BOWLSTYL' => $bowlingStyle,
            'PLAYER_POOL_BATSTYL' => $batStyle);

        $this->_databaseTable = 'PLAYER_POOL';
        $this->_databaseAdapter->update($this->_databaseTable, $playerData, "PLAYER_POOL_ID=$id");

        //Calculate age
        if (!empty($birthDate)) {
            $query = " SELECT DATEDIFF(CURDATE(), '$birthDate') / 365.25 AS age";
            $this->_databaseAdapter->query($query);
            $row = $this->_databaseAdapter->fetch();
            extract($row);
            $age =  $row['age'];

            //Round up
            $age = ceil($age);
            $query = "UPDATE $this->_databaseTable SET PLAYER_POOL_AGE='$age' WHERE PLAYER_POOL_ID='$id'";
            $this->_databaseAdapter->query($query);
       }

    }


    /**
     * Get player id from the player pool
     */

       public function getPlayerId($firstName, $lastName) {
        $this->_databaseTable = 'PLAYER_POOL';
        $this->_databaseAdapter->select($this->_databaseTable, "PLAYER_POOL_FNAME='$firstName' AND PLAYER_POOL_LNAME='$lastName'");
        $resultArray = $this->_databaseAdapter->fetch();
        return $resultArray['PLAYER_POOL_ID'];
    }

     /*
     * \brief get all players by country from player pool
     */

         public function getAllPlayers() {
        $this->_databaseTable = 'TEAM_POOL';
        $query = "SELECT tmp.TEAM_POOL_NAME, pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_DOB, pp.PLAYER_POOL_POB, pp.PLAYER_POOL_AGE, pp.PLAYER_POOL_NNAME, pp.PLAYER_POOL_HT, pp.PLAYER_POOL_PROFL, pp.PLAYER_POOL_FLDNG, pp.PLAYER_POOL_BOWLSTYL, pp.PLAYER_POOL_BATSTYL
                  FROM
                  TEAM_POOL tmp JOIN
                  PLAYER_POOL pp ON tmp.TEAM_POOL_ID = pp.TEAM_POOL_TEAM_POOL_ID
                  ORDER BY tmp.TEAM_POOL_NAME";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }
        return $resultArray;
    }

         /*
     * \brief get player details
     */

         public function getPlayerDetails($playerID) {
        $this->_databaseTable = 'PLAYER_POOL';
        $query = "SELECT tmp.TEAM_POOL_NAME, pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_DOB, pp.PLAYER_POOL_POB, pp.PLAYER_POOL_AGE, pp.PLAYER_POOL_NNAME, pp.PLAYER_POOL_HT, pp.PLAYER_POOL_PROFL, pp.PLAYER_POOL_FLDNG, pp.PLAYER_POOL_BOWLSTYL, pp.PLAYER_POOL_BATSTYL
                  FROM
                  TEAM_POOL tmp JOIN
                  PLAYER_POOL pp ON tmp.TEAM_POOL_ID = pp.TEAM_POOL_TEAM_POOL_ID
                  WHERE pp.PLAYER_POOL_ID = '$playerID'";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }
        return $resultArray;
    }

             /*
     * \brief get players' details from country
     */

         public function getPlayersByPoolID($teamPoolID) {
        $this->_databaseTable = 'PLAYER_POOL';
        $query = "SELECT tmp.TEAM_POOL_NAME, pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_DOB, pp.PLAYER_POOL_POB, pp.PLAYER_POOL_AGE, pp.PLAYER_POOL_NNAME, pp.PLAYER_POOL_HT, pp.PLAYER_POOL_PROFL, pp.PLAYER_POOL_FLDNG, pp.PLAYER_POOL_BOWLSTYL, pp.PLAYER_POOL_BATSTYL
                  FROM
                  TEAM_POOL tmp JOIN
                  PLAYER_POOL pp ON tmp.TEAM_POOL_ID = pp.TEAM_POOL_TEAM_POOL_ID
                  WHERE tmp.TEAM_POOL_ID = '$teamPoolID'";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }
        return $resultArray;
    }

                 /*
     * \brief get players' details from country
     */

         public function getAllBowlers($teamID) {
        $this->_databaseTable = 'PLAYER_POOL';
        $query = "SELECT pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_DOB, pp.PLAYER_POOL_POB, pp.PLAYER_POOL_AGE, pp.PLAYER_POOL_NNAME, pp.PLAYER_POOL_HT, pp.PLAYER_POOL_BOWLSTYL
                  FROM PLAYER_POOL AS pp
                  LEFT JOIN PLAYER AS p ON pp.PLAYER_POOL_ID = p.PLAYER_POOL_PLAYER_POOL_ID
                  LEFT JOIN BOWLER AS b ON p.PLAYER_ID = b.PLAYER_PLAYER_ID
                  WHERE p.TEAM_TEAM_ID = '$teamID'";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }
        return $resultArray;
    }

                /*
     * \brief get players' details from country
     */

         public function getPlayersByPoolName($teamPoolName) {
        $query = "SELECT pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_DOB, pp.PLAYER_POOL_POB, pp.PLAYER_POOL_AGE, pp.PLAYER_POOL_NNAME, pp.PLAYER_POOL_HT, pp.PLAYER_POOL_PROFL, pp.PLAYER_POOL_FLDNG, pp.PLAYER_POOL_BOWLSTYL, pp.PLAYER_POOL_BATSTYL
                  FROM
                  TEAM_POOL tmp JOIN
                  PLAYER_POOL pp ON tmp.TEAM_POOL_ID = pp.TEAM_POOL_TEAM_POOL_ID
                  WHERE tmp.TEAM_POOL_NAME = '$teamPoolName'";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }
        return $resultArray;
    }

     /**
     * Allows a user to mark if a player is a bowler in a particular game
     */

    public function playerIsBowler($playerID, $bowlStyle) {


        if ($_SESSION['admin_level'] == 0) {
            die($this->lang_ini_array['ERRORS']['AdminLevelError']);
        }

        $bowlerData = array(
            'BOWLER_ID' => '',
            'BOWLER_STYL' => $bowlStyle,
            'BOWLER_OVRS' => '0.0',
            'PLAYER_PLAYER_ID' => $playerID);

        $this->_databaseTable = 'BOWLER';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $bowlerData);
        return $id;

}

public function isPlayerWicketkeeper($playerPoolID) {
        $this->_databaseTable = 'PLAYER_POOL';
        $this->_databaseAdapter->select($this->_databaseTable, "PLAYER_POOL_ID = '$playerPoolID'");
        $result = $this->_databaseAdapter->fetch();
        if (preg_match('/^(wicket)[\- ]?(keeper)$/i', $result['PLAYER_POOL_FLDNG'])) {
            return true;
        } else {
            return false;
        }
    }

//Returns false if player is not bowler
    public function isPlayerBowler($playerPoolID) {
        $this->_databaseTable = 'PLAYER_POOL';
        $query = "SELECT LENGTH(PLAYER_POOL_BOWLSTYL) AS Length FROM $this->_databaseTable WHERE PLAYER_POOL_ID = '$playerPoolID'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if($result['Length']>1)
        {
            return true;
        }
        else return false;
        
    }

    //Returns false if player is not specialist batsman
    public function isPlayerSpecialistBatsman($playerPoolID) {
        $this->_databaseTable = 'PLAYER_POOL';
        $bool=TRUE;
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE PLAYER_POOL_BATSPECILST IS TRUE AND PLAYER_POOL_ID = '$playerPoolID'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) == 0 ) {
            return 0;
        } else {
            return 1;
        }
    }

     //Returns false if player is not captain
    public function isPlayerCaptain($playerPoolID, $gameID) {
        $this->_databaseTable = 'PLAYER';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE PLAYER_POOL_PLAYER_POOL_ID = '$playerPoolID' AND TEAM_GAME_GAME_ID = '$gameID'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) == 0) {
            return false;
        } else {
            return true;
        }
    }
        public function updatePlayerOvrs($playerId, $ovrs) {

        $this->_databaseTable = 'BOWLER';
        $query = "UPDATE $this->_databaseTable SET BOWLER_OVRS='$ovrs' WHERE PLAYER_PLAYER_ID='$playerId'";
        $this->_databaseAdapter->query($query);
    }
    
      public function insertBatsmanDetails($playerID, $batStyle, $batOrder, $teamID, $gameID) {

        
        if ($_SESSION['admin_level'] == 0) {
            die($this->lang_ini_array['ERRORS']['AdminLevelError']);
        }

        $batsmanData = array(
            'BATSMAN_ID' => '',
            'BATSMAN_STYL' => $batStyle,
            'BATSMAN_ORDR' => $batOrder,
            'PLAYER_PLAYER' => $playerID,
            'PLAYER_TEAM_TEAM_ID' => $teamID,
            'PLAYER_TEAM_GAME_GAME_ID' => $gameID
            );

        $this->_databaseTable = 'BATSMAN';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $batsmanData);
        return $id;
    }

            public function updateBatsmanDetails($batID, $playerID, $batStyle, $batOrder, $teamID, $gameID) {


        if ($_SESSION['admin_level'] == 0) {
            die($this->lang_ini_array['ERRORS']['AdminLevelError']);
        }

        $batsmanData = array(
            'BATSMAN_BAT_STYL' => $batStyle,
            'BATSMAN_BAT_ORDR' => $batOrder,
            'PLAYER_PLAYER_ID' => $playerID,
            'PLAYER_TEAM_TEAM_ID' => $teamID,
            'PLAYER_TEAM_GAME_GAME_ID' => $gameID
            );

        $this->_databaseTable = 'BATSMAN';
        $this->_databaseAdapter->update($this->_databaseTable, $batsmanData, "BATSMAN_ID=$batID");
    }


             public function getOpeningBatsmen($gameID) {

                 $query = "SELECT pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_BATSTYL
                  FROM
                  PLAYER_POOL pp LEFT JOIN
                  PLAYER p ON pp.PLAYER_POOL_ID = p.PLAYER_POOL_PLAYER_POOL_ID
                  WHERE p.PLAYER_BAT_ORDR = '1' AND p.PLAYER_BAT_ORDR = '2'";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }
        return $resultArray;
    }

      //Delete player from player pool by ID
         public function deletePlayer($playerPoolID) {
        $query = "DELETE FROM PLAYER_POOL WHERE PLAYER_POOL_ID = '$playerPoolID'";
        $this->_databaseAdapter->query($query);
        $rows = $this->_databaseAdapter->getAffectedRows();
        if(empty($rows))
        {
            return false;
        } else {
            return true;
        }
    }

          //Delete all players from the game
         public function deletePlayersFromGame($gameID) {
        $query = "DELETE FROM PLAYER WHERE TEAM_GAME_GAME_ID = '$gameID'";
        $this->_databaseAdapter->query($query);
        $rows = $this->_databaseAdapter->getAffectedRows();
        if(empty($rows))
        {
            return false;
        } else {
            return true;
        }
    }

}

/*
 *
 * END PlayerAdmin.php
 *
 */
?>
